package com.zhuannimei.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.zhuannimei.GlobalApplication;
import com.zhuannimei.R;
import com.zhuannimei.adapter.ProductUserAdapter;
import com.zhuannimei.domain.Product;
import com.zhuannimei.domain.ProductUser;
import com.zhuannimei.net.RequestServerData;
import com.zhuannimei.parser.RankParser;
import com.zhuannimei.utility.JsonUtil;
import com.zhuannimei.utility.UiUtil;
import com.zhuannimei.utility.UserData;
import com.zhuannimei.utility.WuLog;
import com.zhuannimei.utility.YouLog;
import com.zhuannimei.view.ZnmRefreshListView;
import com.zhuannimei.view.ZnmRefreshListView.OnCancelListener;
import com.zhuannimei.view.ZnmRefreshListView.OnRefreshListener;

public class Fragment3 extends BaseFragment implements OnItemClickListener,
		OnCancelListener {
	private ZnmRefreshListView znmRL;// 赚你妹下拉控件
	private static final String TAG = "Fragment3";
	private ProductUserAdapter mAdapter;
	private List<ProductUser> persons = new ArrayList<ProductUser>();

	// 请求排名数据所需的4个参数
	private String userId = UserData.getInstance().getUserUserId().trim();
	private String currentIndex = "0";
	private String currentTimestamp = "1";
	private String currentPageSize = "50";

	// private ArrayList<ProductUser> puList;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		WuLog.i(TAG, "onCreate");
		// 准备数据
		// 先查本地数据
		// 然后查询互联网数据
		try {
			persons.clear();
			List<ProductUser> list = GlobalApplication.appDB
					.findAll(ProductUser.class);
			if (list != null && list.size() != 0) {
				persons.addAll(list);
			}
			// requestRankData(userId, "1", "30", "0");
		} catch (Exception e) {
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment3, container, false);
		return super.onCreateView(inflater, container, savedInstanceState);
		// return inflater.inflate(R.layout.fragment3, container, false);
	}

	@Override
	public void onStart() {
		super.onStart();
		mTitlePane.setTitle("积分榜");
	}

	@Override
	protected void initViews() {

		WuLog.i(TAG, "initViews");
		znmRL = (ZnmRefreshListView) findViewById(R.id.point_me_ZR);
		if (mAdapter == null) {
			requestRankData(userId, "1", "30", "0");
		} else {
			mAdapter = new ProductUserAdapter(getActivity(), persons);
			znmRL.setAdapter(mAdapter);
		}

		// znmRL.setAdapter(mAdapter);
	}

	@Override
	protected void initEvents() {
		znmRL.setOnItemClickListener(this);
		znmRL.setOnCancelListener(this);
	}

	@Override
	protected void initData() {

	}

	@Override
	public void onCancel() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		WuLog.i(TAG, "条目点击操作");

	}

	/**
	 * 从服务器上获取商品列表
	 */
	private void getProductUsFromNeert() {
		putAsyncTask(new AsyncTask<Void, Void, String>() {

			@Override
			protected String doInBackground(Void... params) {
				// SystemClock.sleep(2000);
				persons.clear();
				ProductUser user;
				for (int x = 0; x < 30; x++) {
					user = new ProductUser();
					user.setUserName("用户" + x);
					user.setPoint(60 - x + "");
					persons.add(user);
				}
				// 访问互联网的方法
				WuLog.i(TAG, "异步访问互联网抓取送");
				return "";
			}

			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				WuLog.i(TAG, "执行结束，设置适配器" + result);
				// 成功
				if (mAdapter == null) {
					//
					mAdapter = new ProductUserAdapter(getActivity(), persons);
				}
				znmRL.setAdapter(mAdapter);
				znmRL.onRefreshComplete();
			}
		});
	}

	/**
	 * 请求积分排名的数据
	 * 
	 * @param param1
	 *            userid
	 * @param param2
	 *            时间戳
	 * @param param3
	 *            每一页的条数
	 * @param param4
	 *            页码
	 */
	private void requestRankData(final String param1, final String param2,
			final String param3, final String param4) {
		AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {
			@Override
			protected String doInBackground(Void... params) {
				// Map<String, String> map = new HashMap<String, String>();
				// map.put("userId", param1);
				// map.put("timestamp", param2);
				// map.put("pageSize", param3);
				// map.put("pageIndex", param4);
				// String mapToJson = JsonUtil.mapToJson(map);
				// Map<String, String> map2 = new HashMap<String, String>();
				// map2.put("data", mapToJson);
				// String userRank = RequestServerData.userRank(map2);
				return "";
			}

			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				YouLog.i(TAG, result);
				pd.cancel();
				try {
					if (!TextUtils.isEmpty(result)) {
//						RankParser rp = new RankParser();
//						ArrayList<Object> obj = (ArrayList<Object>) rp
//								.parseJSON(result);
//						persons = (ArrayList<ProductUser>) obj.get(2);
//						String code = (String) obj.get(0);
//						currentTimestamp = (String) obj.get(1);
//						// currentTimestamp = Integer.parseInt(currentTimestamp)
//						// + 1 + "";
					} else {
						UiUtil.showToast("时间戳内服务器无改变返回 code=1（失败）");
					}

					// 将puList中的数据罗列出来
					if (mAdapter == null) {
						mAdapter = new ProductUserAdapter(getActivity(),
								persons);
					}
					znmRL.setAdapter(mAdapter);
					znmRL.onRefreshComplete();
				} catch (Exception e) {
					UiUtil.showToast("登陆失败");
					e.printStackTrace();
				}
			}

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				pd.setMsg("正在努力加载...");
				pd.show();
			}
		};
		asyncTask.execute();
	}

}
